package online.keepon.document.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * JWT工具类
 *
 * @author top
 */
@Slf4j
public class JwtTokenUtil {

    public static final String secret = "Secret:abf685fa57c044c38ddffg9";
    public static final long expire = 12*60*60*1000;

    /**
     * 私有化构造器
     */
    private JwtTokenUtil() {
    }


    /**
     * 生成token
     *
     * @param email email
     * @return token
     */
    public static String createAccessToken(String email) {
        return JWT.create()
                .withSubject(email)
                .withIssuer("identity")
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + expire))
                .sign(Algorithm.HMAC512(secret));
    }

    public static String getSubject(String token) {
        return JWT.decode(token).getSubject();
    }

    public static DecodedJWT parser(String token) {
        if (isExpired(token)) {
            throw new TokenExpiredException("token已过期");
        }
        return JWT.decode(token);
    }

    public static boolean isExpired(String token) {
        try {
            DecodedJWT decode = JWT.require(Algorithm.HMAC512(secret)).build().verify(token);
        } catch (TokenExpiredException | SignatureVerificationException | JWTDecodeException e) {
            log.error("token已过期");
            return true;
        }
        return false;
    }

    public static void verify(String decryptToken) {
        JWT.require(Algorithm.HMAC512(secret)).build().verify(decryptToken);
    }
}
